<script setup lang="ts">
import { ref, reactive, h } from "vue";
import { getListApi, deleteApi } from "/@/api/mes/product";
import { useModal } from '/@/hooks/useModal'
import { useTableNotCheck, useDeleteSucessMessage, useConfirm } from '/@/hooks/useMessage'

// 表格配置
const tableRef = ref<YTableInstance>();
const tableProps = reactive<YTableProps>({
  height: "auto",
  columns: [
    { field: "code", label: "产品编号", filter: true },
    { field: "name", label: "产品名称", filter: true },
    { field: "spec", label: "规格", filter: true },
    { field: "unit", label: "单位" },
    { field: "calcUnit", label: "计量单位" },
    { field: "createTime", label: "创建时间", component: 'ElDatePicker' },
    { field: "createUser", label: "创建人" },
    { field: "updateTime", label: "更新时间", component: 'ElDatePicker' },
    { field: "updateUser", label: "更新人" },
  ],
  remoteConfig: {
    api: getListApi,
    immediate: true
  },
  filters: [{ label: '产品编号/名称', field: 'keyword' }],
  operas: [
    {
      title: '新增',
      type: 'primary',
      onClick: () => viewModal.open({ title: '新增', contentProps: { id: void 0 } })
    },
    {
      title: '修改', onClick: () => {
        handEdit()
      }
    },
    {
      title: '删除', onClick: async () => {
        const rows = await tableRef.value.getCheckRecords(true)
        await useConfirm('warning', '确认删除选中的产品吗？')

        deleteApi(rows.map(s => s.id).join()).then(({ succeeded }) => {
          if (succeeded) {
            useDeleteSucessMessage()
            tableRef.value.loadData()
          }
        })
      }
    }
  ]
});

// 编辑窗口
const isChange = ref(false)
const viewModal = useModal({
  title: '新增',
  width: 1000,
  height: 600,
  content: () => import('./view.vue'),
  contentOn: {
    onChange: () => {
      isChange.value = true
    }
  }
});

viewModal.on('open', () => {
  isChange.value = false
})
viewModal.on('close', () => {
  if (isChange.value) {
    tableRef.value.loadData()
  }
})

const handEdit = ({ row }: any = {}) => {

  let id: number;
  if (!row) {
    const selects = tableRef.value.vxe().getCheckboxRecords()
    if (!selects.length)
      return useTableNotCheck()

    id = selects[0].id
  } else {
    id = row.id
  }

  viewModal.open({
    title: '修改', contentProps: { id }
  })
}

</script>
<template>
  <IndexLayout>
    <YTable v-bind="tableProps" ref="tableRef" @row-dbl-click="handEdit"></YTable>
  </IndexLayout>
</template>
